package com.yaowk.weixin.controller;

import com.feizhou.swagger.annotation.Api;
import com.feizhou.swagger.annotation.ApiOperation;
import com.feizhou.swagger.annotation.Param;
import com.feizhou.swagger.annotation.Params;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.yaowk.common.constant.ServiceCode;
import com.yaowk.common.controller.BaseController;
import com.yaowk.common.kit.I18nKit;
import com.yaowk.system.validator.PlatformIdValidator;
import com.yaowk.weixin.common.Constant;
import com.yaowk.weixin.model.Reply;
import com.yaowk.weixin.model.ReplyInfo;
import com.yaowk.weixin.model.ReplyRelate;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yaowk on 17-8-1.
 */
@Api(tag = "reply", description = "自动回复", url = "/admin/weixin/reply")
@RequiresAuthentication
@RequiresPermissions("weixin:reply")
@Before(PlatformIdValidator.class)
public class ReplyController extends BaseController {

    @ApiOperation(url = "/{replyId}", description = "自动回复详情")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true)
    })
    public void index() {
        Integer id = getParaToInt();
        Reply reply = Reply.dao.findById(id);
        if (ObjectUtil.isNotNull(reply)) {
            List<ReplyInfo> replyInfos = new ArrayList<>();
            reply.put("replyInfos", replyInfos);
            List<ReplyRelate> replyRelates = ReplyRelate.dao.find(Kv.by("reply_id = ", id));
            for (ReplyRelate replyRelate : replyRelates) {
                ReplyInfo replyInfo = ReplyInfo.dao.findById(replyRelate.getInfoId());
                if (ObjectUtil.isNotNull(replyInfo)) {
                    replyInfos.add(replyInfo);
                }
            }
        }
        renderJson(reply);
    }

    @ApiOperation(url = "/list", description = "自动回复列表")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "pageSize", description = "分页大小", defaultValue = "20"),
            @Param(name = "pageNumber", description = "当前页", defaultValue = "1")
    })
    public void list() {
        Integer platformId = getParaToInt("platformId");
        Page<Reply> page = Reply.dao.paginate(getPage(), Kv.by("platform_id = ", platformId));
        renderJson(page);
    }

    @ApiOperation(url = "/add", description = "添加自动回复")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "event", description = "事件类型"),
            @Param(name = "msgType", description = "消息类型"),
            @Param(name = "eventKey", description = "事件参数"),
    })
    @Before(Tx.class)
    @RequiresPermissions("weixin:reply:add")
    public void add() {
        Reply reply = getBean(Reply.class, "", true);
        reply.save();
        renderJson(reply);
    }

    @ApiOperation(url = "/edit", description = "修改自动回复")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "id", description = "id", required = true),
            @Param(name = "event", description = "事件类型"),
            @Param(name = "msgType", description = "消息类型"),
            @Param(name = "eventKey", description = "事件参数"),
    })
    @Before(Tx.class)
    @RequiresPermissions("weixin:reply:edit")
    public void edit() {
        Reply reply = getBean(Reply.class, "", true);
        reply.update();
        renderJson(reply);
    }

    @ApiOperation(url = "/edit/{replyId}", description = "删除自动回复")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
    })
    @Before(Tx.class)
    @RequiresPermissions("weixin:reply:delete")
    public void delete() {
        Integer id = getParaToInt();
        new Reply().setId(id).delete();
        renderSuccess();
    }

    @ApiOperation(url = "/replayInfoList/{replyId}", description = "回复内容列表")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "msgType", description = "消息类型", required = true),
            @Param(name = "pageSize", description = "分页大小", defaultValue = "20"),
            @Param(name = "pageNumber", description = "当前页", defaultValue = "1")
    })
    public void replayInfoList() {
        Integer id = getParaToInt();
        Integer platformId = getParaToInt("platformId");
        String msgType = getPara("msgType");
        if (StrKit.isBlank(msgType)) {
            renderFail(ServiceCode.ERROR, "msgType is empty");
            return;
        }
        List<ReplyRelate> replyRelates = ReplyRelate.dao.find(Kv.by("reply_id = ", id));
        Page<ReplyInfo> page = ReplyInfo.dao.paginate(getPage(), Kv.by("platform_id = ", platformId).set("msg_type = ", msgType));
        Set<Integer> replyInfoIds = new HashSet<>();
        for (ReplyRelate replyRelate : replyRelates) {
            replyInfoIds.add(replyRelate.getInfoId());
        }
        for (ReplyInfo replyInfo : page.getList()) {
            if (replyInfoIds.contains(replyInfo.getId())) {
                replyInfo.put("checked", true);
            } else {
                replyInfo.put("checked", false);
            }
        }
        renderJson(page);
    }

    @ApiOperation(url = "/replyInfoEdit/{replyId}", description = "修改内容关系")
    @Params({
            @Param(name = "platformId", description = "平台id", required = true),
            @Param(name = "replyInfoId", description = "内容id", dataType = "Integer[]")
    })
    @Before(Tx.class)
    @RequiresPermissions("weixin:reply:replyInfoEdit")
    public void replyInfoEdit() {
        Integer replyId = getParaToInt();
        Integer[] replyInfoIds = getParaValuesToInt("replyInfoId");
        if (ArrayUtil.isNotEmpty(replyInfoIds)) {
            if (replyInfoIds.length > 8) {
                renderFail(ServiceCode.ERROR, I18nKit.get("reply_info_large_8", Constant.MODULE_NAME, this));
                return;
            }
            for (Integer id : replyInfoIds) {
                ReplyInfo replyInfo = ReplyInfo.dao.findById(id);
                if (!Constant.MSG_TYPE_NEWS.equals(replyInfo.getMsgType()) && replyInfoIds.length > 1) {
                    renderFail(ServiceCode.ERROR, I18nKit.get("is_not_news_large_1", Constant.MODULE_NAME, this));
                    return;
                }
            }
        }
        // 先删除关系再添加
        List<ReplyRelate> replyRelates = ReplyRelate.dao.find(Kv.by("reply_id = ", replyId));
        for (ReplyRelate replyRelate : replyRelates) {
            replyRelate.delete();
        }
        if (ArrayUtil.isNotEmpty(replyInfoIds)) {
            for (Integer id : replyInfoIds) {
                new ReplyRelate().setReplyId(replyId).setInfoId(id).save();
            }
        }
        renderSuccess();
    }
}
